package com.superzqb.asus.superzqbFragment.superzqbJobShop.Shop;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
import com.squareup.picasso.Picasso;
import com.superzqb.asus.Api.ApiParam;
import com.superzqb.asus.superzqb.R;
import com.superzqb.asus.superzqbFragment.superzqbJobShop.Adapter.StyleListAdapter;
import com.superzqb.asus.superzqbFragment.superzqbJobShop.Bean.CampusGoodsDetailBeanA;
import com.superzqb.asus.superzqbFragment.superzqbJobShop.Bean.CampusGoodsDetailBeanB;
import com.superzqb.asus.superzqbFragment.superzqbJobShop.Bean.CampusGoodsDetailBeanC;
import com.superzqb.asus.superzqbFragment.superzqbJobShop.Bean.CampusShopAllBean;
import com.superzqb.asus.Api.CampusShopApi;
import com.superzqb.asus.superzqbFragment.superzqbJobShop.Bean.ImgUrlBean;
import com.superzqb.asus.superzqbFragment.superzqbJobShop.Shop.Adapter.CommentAdapter;
import com.superzqb.asus.superzqbFragment.superzqbJobShop.Shop.Bean.CommentBean;
import com.superzqb.asus.superzqbUtil.GenCommentsAdapter;
import com.superzqb.asus.superzqbUtil.GeneralFun;
import com.superzqb.asus.superzqbUtil.LoadDialog;
import com.superzqb.asus.superzqbUtil.Url;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

/**
 * Created by asus on 2017/1/22.
 */
public class CampusGoodsDetail extends Activity{
    private Context context;
    String pic;
    int size,pc,gid;//几个类别和库存
    private ArrayList<String> sub;
    private TextView con,buy,money,price,goods,number,choose,goodsDetail,commentList,title;
    private LinearLayout li;
    private Button commit;
    private EditText changeNum;
    private ImageView back,plus,minus,img;
    private ImageView btnClose;
    private PopupWindow v;
    private ConvenientBanner convenient;//顶部广告栏控件
    private List<String> networkImages=new ArrayList<>();
    private ViewGroup.LayoutParams i;
    private boolean status=true;
    protected int mScreenWidth;
    protected int mScreenHeight;
    WindowManager mWindowManager;
    WindowManager.LayoutParams wmParams;
    LinearLayout mFloatLayout;
    ListView  lv;
    StyleListAdapter adapter ;
    private ListView listView;
    private GenCommentsAdapter cadapter;
    private CommentAdapter cmtAdapter;
    //动态数组保存要显示的数据，数据存放在数组中，<键，值>对
    public static ArrayList<Map<String, Object>> list = new ArrayList<>();
    public static List<CommentBean> l = new ArrayList<>();
  /*  SharedPreferences sp;*/
    private List<String> images=new ArrayList<>();
    private Dialog loadingDialog;
    public void getLv() {
        String[] tmp = {"非常喜欢", "赞赞赞", "物超所值"};
        list.clear();
        for (int i = 0; i < 1; i++) {
            Map<String, Object> map = new HashMap<>();
            //键一般为"字符串"
            map.put("user", "user" + i);
            map.put("content", tmp[i % 3]);
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            map.put("time", dateFormat.format(new Date()));
            list.add(map);
        }
    }
    public void getComment(){
        Retrofit retrofit=new GeneralFun().gsonCreate();
        CampusShopApi api=retrofit.create(CampusShopApi.class);
        Call<List<CommentBean>> call=api.getCommentList(1,gid);
        call.enqueue(new Callback<List<CommentBean>>() {
            @Override
            public void onResponse(Call<List<CommentBean>> call, Response<List<CommentBean>> response) {
                if(response.isSuccessful()){
                    List<CommentBean> tmp=response.body();
                    l.clear();
                    if(tmp.size()!=0)
                    for(int i=0;i<1;i++)
                        l.add(tmp.get(i));
                    cmtAdapter=new CommentAdapter(context,l);
                    listView.setAdapter(cmtAdapter);
                    if(loadingDialog!=null)
                    loadingDialog.dismiss();
                }
            }

            @Override
            public void onFailure(Call<List<CommentBean>> call, Throwable throwable) {
                Toast.makeText(context,throwable.getMessage(),Toast.LENGTH_SHORT).show();
            }
        });

    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.campus_shop_goods_detail);
        loadingDialog= LoadDialog.getInstance(this,"正在加载");
        loadingDialog.show();

        initView();
        getLv();

      //  cadapter=new GenCommentsAdapter(context,list);


        //registerForContextMenu(lv);
        /*获取屏幕的宽高*/
        Display d=this.getWindowManager().getDefaultDisplay();
        /*获取布局参数*/
        i=li.getLayoutParams();
        i.height=d.getHeight()/5*2;
        i.width=d.getWidth();


        Intent intent=this.getIntent();
        CampusShopAllBean obj=(CampusShopAllBean)intent.getSerializableExtra("goods");
        List<ImgUrlBean> listImg=obj.getImgs();
            if(listImg.get(0).getId().equals("-1"))
                networkImages.add(ApiParam.imgUrl+"mm.jpg");
            else
                for(int i=0;i<listImg.size();i++)
                    networkImages.add(ApiParam.imgUrl+listImg.get(i).getImg());

        setCarousel();//设置轮播图
        goods.setText(obj.getGoodsname());
        price.setText(obj.getPrice());
        gid=obj.getId();
        pic=obj.getHead_img();
        goodsDetail.setText(obj.getDetail());
        changeHint(obj.getId());
        getComment();

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                toCommentList();
            }
        });
    }
    public void changeSub(ArrayList<String> sub){
        this.sub=sub;
    }


    private void createFloatView() {
        wmParams=new WindowManager.LayoutParams();
        //获取的是LocalWindowManager对象
        mWindowManager= getWindow().getWindowManager();
        //获取的是CompatModeWrapper对象
      /*  mWindowManager = (WindowManager) getApplication().getSystemService(Context.WINDOW_SERVICE);*/

        LayoutInflater inflater = this.getLayoutInflater();//LayoutInflater.from(getApplication());
        mFloatLayout = (LinearLayout) inflater.inflate(R.layout.floating, null);
        mWindowManager.addView(mFloatLayout, setVmParams());
        //setContentView(R.layout.main);
        back = (ImageView)mFloatLayout.findViewById(R.id.back_);
        back.setOnClickListener(listen);
    }
    private WindowManager.LayoutParams setVmParams(){
        wmParams.type = WindowManager.LayoutParams.TYPE_PHONE;
        wmParams.format = PixelFormat.RGBA_8888;
        wmParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        wmParams.gravity = Gravity.LEFT|Gravity.TOP;
        wmParams.x = 20;
        wmParams.y = 20;
        wmParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
        wmParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
        return this.wmParams;
    }

    /*设置轮播图*/
    private void setCarousel() {

        convenient.startTurning(3000);
        convenient.setPages(new CBViewHolderCreator<NetworkImageHolderView>() {
            @Override
            public NetworkImageHolderView createHolder() {
                return new NetworkImageHolderView();
            }
        },networkImages)
                .setPageIndicator(new int[]{R.mipmap.ic_page_indicator, R.mipmap.ic_page_indicator_focused})
                .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL);
        if(loadingDialog!=null)
        loadingDialog.dismiss();
    }

    private void changeHint(int id) {
        Retrofit retrofit=new GeneralFun().scalarsCreate();
        CampusShopApi api=retrofit.create(CampusShopApi.class);
        Call<String> call= api.changeHint(id);
        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {

            }

            @Override
            public void onFailure(Call<String> call, Throwable throwable) {

            }
        });

    }
    private void initView() {
        /*sp=getSharedPreferences("submit",MODE_PRIVATE);*/
        commentList=(TextView)findViewById(R.id.commentList);
        context=CampusGoodsDetail.this;
        con=(TextView)findViewById(R.id.connect);//联系客服
        title=(TextView)findViewById(R.id.title);//联系客服
        btnClose=(ImageView)findViewById(R.id.back);//返回
        li=(LinearLayout)findViewById(R.id.img);//获取布局参数
        buy=(TextView)findViewById(R.id.buy);//购买
        goods=(TextView)findViewById(R.id.goodsname);//商品名
        price=(TextView)findViewById(R.id.goodsprice);//价格
        commentList=(TextView)findViewById(R.id.commentList);//评论列表
        goodsDetail=(TextView)findViewById(R.id.goodsDetail);//
        listView=(ListView) findViewById(R.id.listView);//
        convenient = (ConvenientBanner)findViewById(R.id.convenientBanner);
        con.setOnClickListener(listen);
        buy.setOnClickListener(listen);
        btnClose.setOnClickListener(listen);
        commentList.setOnClickListener(listen);
        title.setText("商品详情");

    }
    public void toCommentList(){
        Intent intent=new Intent(context,CampusShopComment.class);
        intent.putExtra("gid",gid);
        startActivity(intent);
    }
    View.OnClickListener listen= new View.OnClickListener() {
        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.commentList:
                    toCommentList();
                    break;
                case R.id.connect:
                    Toast.makeText(CampusGoodsDetail.this,"点击",Toast.LENGTH_SHORT).show();
                    break;
                case R.id.buy:
                    /*需要判断属性是一类还是两类，应该分开*/
                    setBackgroundAlpha(0.5f);
                    showDetail(pic);
                    break;
                case R.id.price:
                    Toast.makeText(CampusGoodsDetail.this,"点击",Toast.LENGTH_SHORT).show();
                    break;
                case R.id.back:
                    finish();
                    break;
                case R.id.back_:
                    closeDetail(getV());
                    break;
                case R.id.minus:
                    int num=Integer.parseInt(changeNum.getText().toString());
                    num--;
                    if(num>1&&num<pc){
                        minus.setBackground(getResources().getDrawable(R.mipmap.minus));
                        plus.setBackground(getResources().getDrawable(R.mipmap.plus));
                    }else if(num==0&&1==pc){
                        minus.setBackground(getResources().getDrawable(R.mipmap.minus_dis));
                        plus.setBackground(getResources().getDrawable(R.mipmap.plus_dis));
                        num++;
                    }else if(num==0&&pc!=1){
                        minus.setBackground(getResources().getDrawable(R.mipmap.minus_dis));
                        plus.setBackground(getResources().getDrawable(R.mipmap.plus));
                        num++;
                    }
                    changeNum.setText(num+"");

                    break;
                case R.id.plus:
                    int num1=Integer.parseInt(changeNum.getText().toString());
                    num1++;
                    if(num1>1&&num1<pc){
                        minus.setBackground(getResources().getDrawable(R.mipmap.minus));
                        plus.setBackground(getResources().getDrawable(R.mipmap.plus));
                    }else if(num1==2&&1==pc){
                        minus.setBackground(getResources().getDrawable(R.mipmap.minus_dis));
                        plus.setBackground(getResources().getDrawable(R.mipmap.plus_dis));
                        num1--;
                    }else if(num1>pc&&num1!=1){
                        minus.setBackground(getResources().getDrawable(R.mipmap.minus));
                        plus.setBackground(getResources().getDrawable(R.mipmap.plus_dis));
                        num1--;
                    }else if(num1==2&&num1<pc){
                        minus.setBackground(getResources().getDrawable(R.mipmap.minus_dis));
                        plus.setBackground(getResources().getDrawable(R.mipmap.plus));
                        num1--;
                    }
                    changeNum.setText(num1+"");

                    break;
                case R.id.img:
                    Toast.makeText(CampusGoodsDetail.this,"点击",Toast.LENGTH_SHORT).show();
                    break;
                case R.id.commit:
                    size=adapter.getCount();
                    adapter.notifyDataSetChanged();
                    sub=adapter.getSub();
                    if(size==1){
                        if(sub.get(0).equals("-1")){
                            Toast.makeText(CampusGoodsDetail.this,"请选择商品属性",Toast.LENGTH_SHORT).show();
                        }else {

                            Intent intent=new Intent(CampusGoodsDetail.this,CampusGoodsSubmit.class);
                            intent.putExtra("gid",gid);
                            intent.putExtra("aa",sub.get(0));
                            intent.putExtra("bb",sub.get(1));
                            intent.putExtra("count",changeNum.getText().toString());
                            intent.putExtra("sum",pc+"");

                            startActivity(intent);
                        }
                    }else if(size==2){

                        if(sub.get(0).equals("-1")||sub.get(1).equals("-1")){
                            Toast.makeText(CampusGoodsDetail.this,"请把商品属性补全",Toast.LENGTH_SHORT).show();

                        }else{

                            Intent intent=new Intent(CampusGoodsDetail.this,CampusGoodsSubmit.class);
                            intent.putExtra("gid",gid);
                            intent.putExtra("aa",sub.get(0));
                            intent.putExtra("bb",sub.get(1));
                            intent.putExtra("count",changeNum.getText().toString());
                            intent.putExtra("sum",pc+"");

                            startActivity(intent);

                        }
                    }

                    break;
                default:
                    break;
            }
        }
    };

    private void closeDetail(PopupWindow view) {
        view.dismiss();
       new popWindowDismiss(1f);
    }

    public PopupWindow getV() {
        return v;
    }

    public void setV(PopupWindow v) {
        this.v = v;
    }

    /*设置popupWindow*/
    private void showDetail(String pic) {
        View detailView=View.inflate(this,R.layout.campus_shop_goods_buy_window,null);
        int width=getResources().getDisplayMetrics().widthPixels;//获取屏幕宽度
        int height=getResources().getDisplayMetrics().heightPixels;//获取屏幕高度
        PopupWindow newView=new PopupWindow(detailView,width,height/5*3);//创建一个popupwindow
        newView.setAnimationStyle(R.style.campus_goods_ani);//设置window滑出动画
        /*点击空白处消失window*/
        newView.setFocusable(true);//设置window可以获取焦点
        newView.setOutsideTouchable(true);//设置允许在外点击消失
        newView.setBackgroundDrawable(new BitmapDrawable(getResources(),(Bitmap)null));
        newView.showAtLocation(detailView, Gravity.BOTTOM,0,0);
        newView.setOnDismissListener(new popWindowDismiss(1f));
        initPopView(detailView,pic);//绑定popWindow里面控件的事件
        setV(newView);
    }
    private void initPopView(View view, String pic) {
        money=(TextView)view.findViewById(R.id.price);//价格
        number=(TextView)view.findViewById(R.id.count);//库存
        back=(ImageView)view.findViewById(R.id.back_);//返回
        lv=(ListView)view.findViewById(R.id.listview);//属性页
        plus=(ImageView)view.findViewById(R.id.plus);//+
        minus=(ImageView)view.findViewById(R.id.minus);//-
        changeNum=(EditText)view.findViewById(R.id.number);//购买数量
        img=(ImageView)view.findViewById(R.id.img);//商品图片
        choose=(TextView)view.findViewById(R.id.choose);//

        commit=(Button)view.findViewById(R.id.commit);//确定购买
        Picasso.with(view.getContext()).load(new Url().getImg_url() +pic).resize(120,120).centerCrop().into(img);
        /*绑定事件*/
        plus.setOnClickListener(listen);
        changeNum.setOnClickListener(listen);
        minus.setOnClickListener(listen);
        //money.setOnClickListener(listen);
        back.setOnClickListener(listen);
        img.setOnClickListener(listen);
        commit.setOnClickListener(listen);
        getData(gid);
    }

    private void getData(int gid) {
        Retrofit retrofit=new GeneralFun().gsonCreate();
        CampusShopApi api=retrofit.create(CampusShopApi.class);
        Call<CampusGoodsDetailBeanA> call=api.getGoodsDetailInfo(gid);
        call.enqueue(new Callback<CampusGoodsDetailBeanA>() {
            @Override
            public void onResponse(Call<CampusGoodsDetailBeanA> call, Response<CampusGoodsDetailBeanA> response) {
                if(response.isSuccessful()){
                    CampusGoodsDetailBeanA res=response.body();
                    money.setText(res.getPrice());
                    pc=Integer.valueOf(res.getCount());
                    number.setText("库存:"+pc+"件");
                    ArrayList<HashMap<String,Object>> a=new ArrayList<HashMap<String,Object>>();//a必须声明为局部变量，不然类别会多次加载
                        int typenum = Integer.parseInt(res.getFlag().trim()) + 1;
                        for (int ii = 0; ii < typenum; ii++) {
                            HashMap<String, Object> tmp = new HashMap<String, Object>();
                            CampusGoodsDetailBeanB tmpb = res.getList().get(ii);
                            tmp.put("type", tmpb.getName());
                            ArrayList<String> b = new ArrayList<>();
                            for (int j = 0; j < tmpb.getLabel().size(); j++) {
                                CampusGoodsDetailBeanC tmpc = tmpb.getLabel().get(j);
                                b.add(tmpc.getName());
                            }
                            tmp.put("label", b);
                            a.add(tmp);
                        }
                    adapter=new StyleListAdapter(CampusGoodsDetail.this,a,choose);//创建适配器
                    lv.setAdapter(adapter);//设置适配器

                    }
                }
            @Override
            public void onFailure(Call<CampusGoodsDetailBeanA> call, Throwable throwable) {
                //Toast.makeText(CampusGoodsDetail.this,"类别获取失败",Toast.LENGTH_SHORT).show();
            }
        });

    }

    //设置透明度
    public void setBackgroundAlpha(float backgroundAlpha) {
        WindowManager.LayoutParams  l = getWindow().getAttributes();
        l.alpha= backgroundAlpha;
        getWindow().setAttributes(l);
    }


    /*把半透明背景还原*/
    class popWindowDismiss implements PopupWindow.OnDismissListener{
        float value;
        public popWindowDismiss(float a){
            this.value=a;
        }
        @Override
        public void onDismiss() {
            setBackgroundAlpha(value);
        }
    }
    public class NetworkImageHolderView  implements Holder<String> {
        private ImageView imageView;
        @Override
        public View createView(Context context) {
            imageView = new ImageView(context);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            return imageView;
        }

        @Override
        public void UpdateUI(Context context, int position, String data) {

            Picasso.with(CampusGoodsDetail.this).load(data).resize(i.width, i.height).into(imageView);
        }
    }


    
}
